package com.lihepeng.leecode.thread;

/**
 * 手动实现读写锁
 * 读读不互斥
 * 读写互斥
 * 写写互斥
 */
// 简单读写锁
public class ReadWriteLock {
    private int readers = 0;
    private int writers = 0;
    private int writerReqests = 0;

    public synchronized void lockRead() throws InterruptedException {
        while (writers > 0 || writerReqests > 0) {
            wait();
        }
        readers++;
    }

    public synchronized void unlockRead() {
        readers--;
        notifyAll();
    }

    public synchronized void lockWrite() throws InterruptedException {
        writerReqests++;
        while (readers > 0 || writers > 0) {
            wait();
        }
        writerReqests--;
        writers++;
    }

    public synchronized void unlockWrite() {
        writers--;
        notifyAll();
    }

}
